# coding:utf-8
import logging
import commands
import tap_config
import ssh_client

logger = None
sshclt = None

# 创建日志处理对象
def create_logger():
    global logger
    # 创建一个logger
    logger = logging.getLogger('TAPLOG')
    logger.setLevel(logging.DEBUG)

    # 创建一个handler，用于写入日志文件
    fh = logging.FileHandler('tap.log')
    fh.setLevel(logging.DEBUG)

    # 再创建一个handler，用于输出到控制台
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)

    # 定义handler的输出格式
    formatter = logging.Formatter("[%(asctime)s]--[%(levelname)s]: %(message)s")
    fh.setFormatter(formatter)
    ch.setFormatter(formatter)

    # 给logger添加handler
    logger.addHandler(fh)
    logger.addHandler(ch)

    return logger

# 记录一条日志
def LOG(msg):
    logger.info(msg)

# 从文件中读取pub_key信息
def read_key_file(file_name):
    """
    Read SSH_RSA key file.
    """
    file = None
    try :
        file = open(file_name)
        print '[INFO ] = SSH_KEY File Open Success.'
    except:
        print '[ERROR] = SSH_KEY File Open Failure.'
    lines = file.readlines()
    key = ''
    for i in range(1, len(lines)-1) :
        key = key + lines[i]
    return key

# 初始化SSH客户端实例
def create_ssh_client():
    global sshclt
    rsa_key = read_key_file(tap_config.keyfile)
    sshclt = ssh_client.TapSSHClient(tap_config.hostsite, tap_config.username, tap_config.password, rsa_key)

# 执行命令行，被handle_cmd_event调用
def execute_cmd_line(command_line):
    '''
    步骤：
    1. 生成需要执行的命令行
    2. 执行对应的命令行
    :return status, result, error:
      *  status =  0 --> success成功
         status = -1 --> failure失败
      *  result --> 返回结果
      *  error  --> 返回错误
    '''
    status = 0
    result = None
    error = None
    if tap_config.local:
        # 本地调用，使用commands库中的getstatusoutput函数来完成处理过程
        return_code, return_content = commands.getstatusoutput(command_line)
        print "return code = ", return_code
        print "return content = ", return_content
        if return_code == 0:
            result = return_content.splitlines()
        else:
            status = -1
    else:
        # 通过SSH调用，使用SSHClient进行命令处理
        stdout, stderr = sshclt.execute_command(command_line)
        out = stdout.read()
        err = stderr.read()
        print out
        if len(err.splitlines()) == 0:
            result = out
        else:
            status = -1
            error = err

    return (status, result, error)